package com.app.business.service;

import com.app.business.model.ZsProject;
import com.app.business.model.ZsProjectHouse;
import com.app.system.jpa.JpaBaseDao;
import com.app.system.utils.CollectionUtils;
import com.app.system.utils.ParamUtils;
import com.app.system.utils.dataType.StringUtils;
import com.app.system.utils.exception.Precondition;
import com.app.system.utils.exception.Response;
import com.google.common.collect.Maps;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 安置房源分配
 * Created by yby on 2019/2/14 17:56.
 */
@Service
@Transactional
public class ZsProjectHouseService extends JpaBaseDao<ZsProjectHouse, Integer> {

    @Autowired
    private HouseService houseService;
    @Autowired
    private ZsProjectService zsProjectService;


    /**
     * 得到征收项目某栋楼中已经分配的房源
     *
     * @param zsProjectId
     * @param azProjectId
     * @param buildNum
     * @return
     */
    public Map<String, String> getHouseIdMap(Integer zsProjectId, Integer azProjectId, String buildNum) {
        String sql = "select house_id from zs_project_house zph where zph.zs_project_id = :zsProjectId and " +
                "house_id in (select id from house h where h.az_project_id = :azProjectId and h.build_num = :build_num)";
        Map<String, Object> param = Maps.newHashMap();
        param.put("zsProjectId", zsProjectId);
        param.put("azProjectId", azProjectId);
        param.put("build_num", buildNum);

        List list = this.findSqlObject(sql, param);
        Map<String, String> map = Maps.newHashMap();
        if (CollectionUtils.isNotEmpty(list)) {
            for (Object o : list) {
                map.put(String.valueOf(o), String.valueOf(o));
            }
        }
        return map;
    }


    /**
     * 保存房源权限
     *
     * @param request
     */
    public synchronized void saveZsProjectHouse(HttpServletRequest request) {
        Integer azProjectId = ParamUtils.getInt(request, "azProjectId", 0);
        String buildNum = ParamUtils.getString(request, "buildNum", "");
        String[] houseId = ParamUtils.getStringParameters(request, "houseIds");
        Integer zsProjectId = ParamUtils.getInt(request, "zsProjectId", 0);

        //删除以前的房源权限
        this.deleteBeforeInfo(azProjectId, buildNum, zsProjectId);
        for (String s : houseId) {
            if (StringUtils.isNotEmpty(s)) {
                ZsProjectHouse zsProjectHouse = new ZsProjectHouse();
                zsProjectHouse.setHouseId(Integer.valueOf(s));
                zsProjectHouse.setZsProjectId(zsProjectId);
                this.save(zsProjectHouse);
            }
        }

    }


    /**
     * 删除以前的房源权限
     *
     * @param azProjectId
     * @param buildNum
     * @param zsProjectId
     */
    private void deleteBeforeInfo(Integer azProjectId, String buildNum, Integer zsProjectId) {
        String sql = "delete from zs_project_house where zs_project_id = :zsProjectId and " +
                "house_id in (select id from house h where h.az_project_id = :azProjectId and h.build_num = :build_num)";
        Map<String, Object> param = Maps.newHashMap();
        param.put("zsProjectId", zsProjectId);
        param.put("azProjectId", azProjectId);
        param.put("build_num", buildNum);
        this.executeSql(sql, param);
    }

    /**
     * 得到某个安置项目某栋楼的全部houseId
     *
     * @param azProjectId
     * @param buildNum
     * @return
     */
    public List<Integer> getHouseIdList(Integer azProjectId, String buildNum) {
        String sql = "select id from house h where h.az_project_id = :azProjectId and h.build_num = :build_num";
        Map<String, Object> param = Maps.newHashMap();
        param.put("azProjectId", azProjectId);
        param.put("build_num", buildNum);
        return (List<Integer>) this.findSqlObject(sql, param);
    }

    /**
     * 根据houseId得到这些房源被分配给了哪些项目，每个项目多少套
     *
     * @param houseIdList
     * @return
     */
    public Map<String, Integer> getZsProjectHouseCountMap(List<Integer> houseIdList) {
        String sql = "select zs_project_id,count(id) from zs_project_house where house_id in (:houseIdList) group by zs_project_id";
        Map<String, Object> param = Maps.newHashMap();
        param.put("houseIdList", houseIdList);
        List list = this.findSqlObject(sql, param);
        Map<String, Integer> map = new HashMap<>();
        if (CollectionUtils.isNotEmpty(list)) {
            for (Object o : list) {
                Object[] os = (Object[]) o;
                map.put(String.valueOf(os[0]), Integer.valueOf(String.valueOf(os[1])));
            }
        }
        return map;
    }

    /**
     * 房源分配批量导入保存
     * @param request
     * @return
     */
    @Transactional
    public synchronized Response batchFormSave(HttpServletRequest request){
        Integer zsProjectId = ParamUtils.getInt(request,"zsProjectId",0);
        String houseIdStr = request.getParameter("houseIdStr");
        ZsProject zsProject = this.zsProjectService.findOne(zsProjectId);
        Precondition.checkAjaxArguement(!houseIdStr.equals(""),"1111","不允许导入空数据！");
        Precondition.checkAjaxArguement(zsProject != null,"2222","数据错误！");
        List<Integer> houseIdList = this.houseService.getHouseIdListByZsProjectId(zsProject.getId());
        Integer successCount = 0;   //导入成功个数
        Integer falseCount = 0;   //导入失败个数
        Integer existsCount = 0;  //导入失败其中已存在个数
        String[] houseIdArray = houseIdStr.split("\n");
        if (houseIdArray != null && houseIdArray.length > 1){
            for (String s : houseIdArray){
                //若此行数据为空，跳过，导入失败计数+1
                if (s == null || s.trim().equals("")){
                    falseCount++;
                    continue;
                }

                Integer houseId = Integer.valueOf(s);
                //如果此房源已存在，跳过，无需导入
                if (houseIdList.contains(houseId)){
                    falseCount++;   //导入失败计数+1
                    existsCount++;   //导入失败其中已存在个数+1
                    continue;
                }

                //以上均通过，则直接插入此条数据
                successCount++;
                ZsProjectHouse zsProjectHouse = new ZsProjectHouse();
                zsProjectHouse.setZsProjectId(zsProject.getId());
                zsProjectHouse.setHouseId(houseId);
                this.save(zsProjectHouse);
            }
        }
        return new Response("0001","本次操作导入成功【"+successCount+"】条数据,导入失败【"+falseCount+"】条数据(其中数据已存在导致导入失败"+existsCount+"条)");
    }
}
